package xuli.servlet;

import com.alibaba.fastjson.JSON;
import entity.Product_Comment;
import util.PageUtil;
import xuli.service.ProductCommentService;
import xuli.service.impl.ProductCommentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author xuli
 */
@WebServlet("/ProductCommentServlet")
public class ProductCommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");


        ProductCommentService productCommentService = new ProductCommentServiceImpl();

        String productId = request.getParameter("product_id");

        String pageNo = request.getParameter("pageNo");

        if (pageNo == null || "".equals(pageNo.trim())) {
            pageNo = "1";
        }
        response.setContentType("application/json;charset=utf-8");
        PageUtil<Product_Comment> product_commentPageUtil = new PageUtil<>(Integer.parseInt(pageNo), 2, productCommentService.getTotalCount(productId));

        List<Product_Comment> comments = productCommentService.findByPages(product_commentPageUtil, productId);

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();

        stringObjectHashMap.put("pageNo", product_commentPageUtil.getPageNo());

        stringObjectHashMap.put("comments", comments);

        stringObjectHashMap.put("pageUtil", product_commentPageUtil);

        String s = JSON.toJSONString(stringObjectHashMap);

        response.getWriter().print(s);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
